package com.example.j202411.adapter;

import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.j202411.R;
import com.example.j202411.Model.ChatMessage;

import java.util.List;

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolder> {

    private List<ChatMessage> chatMessages;
    private Handler handler = new Handler(Looper.getMainLooper());

    public ChatAdapter(List<ChatMessage> chatMessages) {
        this.chatMessages = chatMessages;
    }

    @NonNull
    @Override
    public ChatViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView;
        if (viewType == ChatMessage.TYPE_USER) {
            itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user_message, parent, false);
        } else {
            itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_message, parent, false);
        }
        return new ChatViewHolder(itemView, viewType);
    }

    @Override
    public void onBindViewHolder(@NonNull ChatViewHolder holder, int position) {
        ChatMessage chatMessage = chatMessages.get(position);
        holder.tvMessage.setText(chatMessage.getMessage());

        if (chatMessage.isAiMessage()) {
            if (chatMessage.isLoading()) {
                if (holder.loadingIndicator != null) {
                    holder.loadingIndicator.setVisibility(View.VISIBLE);
                    holder.tvMessage.setVisibility(View.INVISIBLE);
                    startAnimations(holder);
                }
            } else {
                if (holder.loadingIndicator != null) {
                    stopAnimations(holder);
                    holder.loadingIndicator.setVisibility(View.GONE);
                }
                holder.tvMessage.setVisibility(View.VISIBLE);
            }
        } else {
            if (holder.loadingIndicator != null) {
                stopAnimations(holder);
                holder.loadingIndicator.setVisibility(View.GONE);
            }
            holder.tvMessage.setVisibility(View.VISIBLE);
        }
    }

    private void startAnimations(final ChatViewHolder holder) {
        if (holder.loadingAnimation != null) {
            startSingleAnimation(holder.loadingAnimation, () -> {
                if (holder.loadingAnimation2 != null) {
                    startSingleAnimation(holder.loadingAnimation2, () -> {
                        if (holder.loadingAnimation3 != null) {
                            startSingleAnimation(holder.loadingAnimation3, () -> {
                                handler.postDelayed(() -> {
                                    if (holder.loadingAnimation != null) {
                                        startAnimations(holder); // 重新启动动画
                                    }
                                }, 500);
                            });
                        }
                    });
                }
            });
        }
    }

    private void startSingleAnimation(final AnimationDrawable animation, final Runnable onAnimationEnd) {
        if (animation != null && !animation.isRunning()) {
            animation.start();
            int totalDuration = getAnimationTotalDuration(animation);
            handler.postDelayed(() -> {
                if (animation != null && animation.isRunning()) {
                    animation.stop();
                    onAnimationEnd.run();
                }
            }, totalDuration);
        }
    }

    private void stopAnimations(ChatViewHolder holder) {
        if (holder.loadingAnimation != null && holder.loadingAnimation.isRunning()) {
            holder.loadingAnimation.stop();
        }
        if (holder.loadingAnimation2 != null && holder.loadingAnimation2.isRunning()) {
            holder.loadingAnimation2.stop();
        }
        if (holder.loadingAnimation3 != null && holder.loadingAnimation3.isRunning()) {
            holder.loadingAnimation3.stop();
        }
    }

    private int getAnimationTotalDuration(AnimationDrawable animation) {
        int totalDuration = 0;
        for (int i = 0; i < animation.getNumberOfFrames(); i++) {
            totalDuration += animation.getDuration(i);
        }
        return totalDuration;
    }

    @Override
    public int getItemCount() {
        return chatMessages.size();
    }

    @Override
    public int getItemViewType(int position) {
        return chatMessages.get(position).getType();
    }

    public void addMessage(ChatMessage message) {
        chatMessages.add(message);
        notifyItemInserted(chatMessages.size() - 1);
    }

    public void updateMessage(int position, String message) {
        if (position >= 0 && position < chatMessages.size()) {
            ChatMessage chatMessage = chatMessages.get(position);
            if (chatMessage.isAiMessage() && chatMessage.isLoading()) {
                chatMessage.setMessage(message);
                chatMessage.setLoading(false);
                notifyItemChanged(position);
            }
        }
    }

    public class ChatViewHolder extends RecyclerView.ViewHolder {
        TextView tvMessage;
        View loadingIndicator;
        AnimationDrawable loadingAnimation;
        AnimationDrawable loadingAnimation2;
        AnimationDrawable loadingAnimation3;

        public ChatViewHolder(@NonNull View itemView, int viewType) {
            super(itemView);
            tvMessage = itemView.findViewById(R.id.tvMessage);
            if (viewType == ChatMessage.TYPE_AI) {
                loadingIndicator = itemView.findViewById(R.id.loadingIndicator);
                ImageView loadingDot1 = itemView.findViewById(R.id.dot1);
                ImageView loadingDot2 = itemView.findViewById(R.id.dot2);
                ImageView loadingDot3 = itemView.findViewById(R.id.dot3);
                if (loadingDot1 != null && loadingDot2 != null && loadingDot3 != null) {
                    loadingDot1.setBackgroundResource(R.drawable.dot1_animation);
                    loadingAnimation = (AnimationDrawable) loadingDot1.getBackground();

                    loadingDot2.setBackgroundResource(R.drawable.dot2_animation);
                    loadingAnimation2 = (AnimationDrawable) loadingDot2.getBackground();

                    loadingDot3.setBackgroundResource(R.drawable.dot3_animation);
                    loadingAnimation3 = (AnimationDrawable) loadingDot3.getBackground();
                } else {
                    loadingAnimation = null;
                    loadingAnimation2 = null;
                    loadingAnimation3 = null;
                }
            } else {
                loadingIndicator = null; // 如果是用户消息，不需要加载指示器
                loadingAnimation = null;
                loadingAnimation2 = null;
                loadingAnimation3 = null;
            }
        }
    }
}